<template>
  <div id="picture-manager-page">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/add-picture" target="_blank">+ 新增图片</a-button>
        <a-button type="primary" href="/add-picture/batch" target="_blank" ghost>+ 批量创建图片</a-button>
      </a-space>
    </a-flex>
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键字" name="searchText">
        <a-input v-model:value="searchParams.searchText" placeholder="从名称和简介搜索" allowClear>
        </a-input>
      </a-form-item>
      <a-form-item label="类型" name="picFormat">
        <a-input v-model:value="searchParams.picFormat" placeholder="类型" allowClear></a-input>
      </a-form-item>
      <a-form-item label="标签" name="picFormat">
        <a-select
          v-model:value="searchParams.tags"
          mode="tags"
          style="min-width: 180px"
          placeholder="请输入标签"
          allowClear
        ></a-select>
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PICTURE_REVIEW_STATUS_OPTIONS"
          style="min-width: 180px"
          placeholder="请选择审核状态"
          allowClear
        ></a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit"> 搜索 </a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px"></div>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name'">
          <span> Name </span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :width="120" :src="record?.url" />
        </template>
        <!-- 标签 -->
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="(tag, index) in JSON.parse(record?.tags || '[]')" :key="index">
              {{ tag }}
            </a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewInfo'">
          <div>审核状态：{{ PICTURE_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.key === 'action'">
          <div class="button_box">
            <a-space wrap>
              <a-button type="link" :href="`/add-picture?id=${record.id}`"> 编辑</a-button>
              <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
              <a-button
                v-if="record.reviewStatus !== PICTURE_REVIEW_STATUS_ENUM.PASS"
                type="link"
                @click="handleReview(record, PICTURE_REVIEW_STATUS_ENUM.PASS)"
                >通过</a-button
              >
              <a-button
                type="link"
                v-if="record.reviewStatus !== PICTURE_REVIEW_STATUS_ENUM.REJECT"
                danger
                @click="handleReview(record, PICTURE_REVIEW_STATUS_ENUM.REJECT)"
                >拒绝</a-button
              >
            </a-space>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  deletePictureUsingPost,
  listPictureByPageUsingPost,
  reviewPictureUsingPost
} from '@/request/api/pictureController'
import {
  PICTURE_REVIEW_STATUS_ENUM,
  PICTURE_REVIEW_STATUS_MAP, PICTURE_REVIEW_STATUS_OPTIONS
} from '@/constants/pictureConstant.ts'
const searchParams = reactive<API.PictureQueryRequest>({
  pageNum: 1,
  pageSize: 10,
  sortFields: ['createTime'],
  sortOrders: [0],
})

const total = ref(0)
const dataSource = ref<Array<API.Picture>>([])

const pagination = computed(() => ({
  total: Number(total.value),
  current: searchParams.pageNum ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  showSizeChanger: true,
  showTotal: (total: number) => `共${total}条`,
}))

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
  },
  {
    title: '审核信息',
    dataIndex: 'reviewInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]
// 获取数据
const featureData = async () => {
  try {
    const params:API.PictureQueryRequest={
      ...searchParams,
      nullSpaceId:true
    }
    const { data: res } = await listPictureByPageUsingPost(params)
    if (res?.code === 0 && res?.data) {
      total.value = res.data.total ?? 0
      dataSource.value = res.data.records ?? []
    } else {
      message.error(res?.message || '获取数据失败')
    }
  } catch (error) {
    message.error('获取数据失败')
  }
}
const handleTableChange = (pagination: any) => {
  // 表数据发生改变时
  searchParams.pageSize = pagination.pageSize
  searchParams.pageNum = pagination.current
  featureData()
}
const doSearch = () => {
  // 搜索
  searchParams.pageNum = 1
  featureData()
}
const doDelete = async (id: number) => {
  // 删除用户
  const { data:res } = await deletePictureUsingPost({ id: id })
  if (res.code == 0 && res.data) {
    message.success('删除成功')
    featureData()
  } else {
    message.error('删除失败')
  }
}
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const { data: res } = await reviewPictureUsingPost({
    id: record.id,
    reviewStatus: reviewStatus,
    reviewMessage:
      reviewStatus === PICTURE_REVIEW_STATUS_ENUM.PASS ? '管理员通过审核' : '管理员拒绝审核',
  })
  if (res.code == 0 && res.data) {
    message.success('审核操作成功')
    featureData()
  } else {
    message.error('审核操作失败')
  }
}
// 页面加载时调用
onMounted(() => {
  featureData()
})
</script>
<style lang="less" scoped></style>
